package com.github.thinwonton.cas.showcase.common;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class DigestUtils {
    private static SecureRandom secureRandom = new SecureRandom();

    private static int defaultSaltSize = 32;

    public static String digest(String s, String algorithm) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            byte[] bytes = messageDigest.digest(s.getBytes("UTF-8"));
            return Hex.encodeHexString(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String salt() {
        return salt(defaultSaltSize);
    }

    public static String salt(int size) {
        byte[] salt = saltInternal(size);
        return getSaltAsString(salt);
    }


    private static byte[] saltInternal(int size) {
        byte[] salt = new byte[size];
        secureRandom.nextBytes(salt);
        return salt;
    }

    private static String getSaltAsString(byte[] salt) {
        return Base64.encodeBase64String(salt);
    }
}
